package com.honeybee.cloud.framework.gateway.filter;

import com.honeybee.cloud.framework.base.enums.HeaderEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description 头部filter
 * @Author DELL
 * @Create 2019-06-10
 * @Since 1.0.0
 */
@Slf4j
@Component
public class HeaderFilter implements GlobalFilter, Ordered {

    /**
     * 全局过滤器 核心方法
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始判断请求头部信息");
        String url = exchange.getRequest().getURI().toString();
        boolean isMatchURL = url.contains("health") || url.contains("oauth");
        if (isMatchURL) {
            log.info("不需要判断头部信息");
            return chain.filter(exchange);
        }
        String appKey = exchange.getRequest().getHeaders().getFirst(HeaderEnum.APP_KEY.getCode());
        log.info("请求头部信息:{},{}", HeaderEnum.APP_KEY.getCode(), appKey);
        if (StringUtils.isBlank(appKey)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }


    /**
     * 数字越低优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -200;
    }
}
